<template>
  <common-select
    :options="taskOptions"
    :defaultValue="defaultTaskId"
    @changeoption="changeOption"
    :allow-clear="clear"
    :show-search="true"
    :disabled="readonly"
    :placeholder="placeholder ? placeholder : $t('pleaseSelect') + $t('campaign').toLowerCase()"
    :mode="mode"
    :max-tag-count="maxTagCount"
    :loading="loading"
  ></common-select>
</template>
<script>
// 任务下拉数据
import CommonSelect from '@/components/SelfComponents/CommonSelect.vue'
import taskApi from '@/api/modules/task'
export default {
  components: {
    CommonSelect
  },
  props: {
    defaultTaskId: {
      type: [String, Object, Array],
      default () {
        return undefined
      }
    },
    time: {
      type: [Number, Object],
      default () {
        return null
      }
    },
    readonly: {
      type: Boolean,
      default: false
    },
    query: {
      type: Object,
      default () {
        return {}
      }
    },
    mode: {
      type: String,
      default: 'default'
    },
    maxTagCount: {
      type: Number,
      default: 1
    },
    clear: {
      type: Boolean,
      default: false
    },
    init: {
      type: Boolean,
      default: true
    },
    //是否默认选中最新选项
    defaultChooseLatestIdFlag: {
      type: Boolean,
      default: false
    },
    //提示
    placeholder: {
      type: String,
      default: ''
    },
  },
  data () {
    return {
      taskOptions: [],
      loading:false,
    }
  },
  watch: {
    time: {
      handler () {
        this.getData()
      },
      immediate: true
    },
    watch: {
      query: {
        handler () {
          this.getData()
        },
        deep: true,
        immediate: true
      }
    }
  },
  created () {
  },
  methods: {
    getData () {
      this.taskOptions = []
      if (!this.init) {
        return
      }
      this.loading=true
      taskApi.getTaskSelect(this.query).then((res) => {
        this.taskOptions = res.data.map(item => {
          let { name } = item
          if (item.type === 10) {
            name += '[' + this.$t('cycleTestTask') + ']'
          }
          return {
            id: item.id,
            name
          }
        })
        if (!this.defaultTaskId && this.defaultChooseLatestIdFlag && this.taskOptions.length) {
          this.changeOption(this.taskOptions[0].id)
        }
      }).finally(() => {
        this.loading = false
      })
    },
    changeOption (val) {
      this.$emit('changeoption', val)
    }
  }
}
</script>
